package top.kaoshanji.ch06.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * author kaoshanji
 * ^_^
 * create time 2024/11/27 16:28
 */
public class TraceHandler implements InvocationHandler {

    private Object target;

    public TraceHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // 打印 implicit 参数
        System.out.print(target);

        // 打印方法名称
        System.out.print("." + method.getName() + "(");

        // 打印 explicit 参数
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                System.out.print(args[i]);
                if (i < args.length - 1) System.out.print(", ");
            }
        }
        System.out.println(")");

        // 调用 actual 方法
        return method.invoke(target, args);
    }
}
